package com.xhui.collection.list;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Author XHui
 * @Date 2023/1/31 9:19
 * @Version 1.0
 */
public class ArrayListDemo {

    public static void main(String[] args) {
        ArrayList<String> strList = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            strList.add(String.valueOf(i));
        }
        System.out.println(strList);
        System.out.println("size: " + strList.size());
        System.out.println("capacity: " + getCapacity(strList));

        for (int i = 10; i >= 0; i--) {
            strList.remove(i);
        }
        System.out.println(strList);
        System.out.println("size: " + strList.size());
        System.out.println("capacity: " + getCapacity(strList));
    }

    /**
     * 通过反射获取ArrayList的私有字段 elementData
     * @param arrayList
     * @return
     * @throws Exception
     */
    public static int getCapacity(ArrayList<?> arrayList)  {
        //
        Class<ArrayList> arrayListClass = ArrayList.class;
        try {
            Field field = arrayListClass.getDeclaredField("elementData");
            field.setAccessible(true); // 强行访问
            Object[] objects = (Object[]) field.get(arrayList);
            return objects.length;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return -1;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return -1;
        }
    }
}
